#include <iostream>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>

// const std::string g_ip = "127.0.0.1";
const uint16_t g_port = 8080;

int main()
{
    //1.创建socket
    int socketfd = ::socket(AF_INET,SOCK_DGRAM,0);
    if(socketfd < 0)
    {
        std::cerr << "create socket fail!";
        return -1;
    }
    std::cerr << "create socket success!"<< std::endl;
    sockaddr_in local;
    memset(&local,sizeof(local),0);
    local.sin_family = AF_INET;
    local.sin_addr.s_addr = INADDR_ANY;
    local.sin_port = ::htons(g_port);//本地转网络

    //2. 绑定
    int n = ::bind(socketfd,(sockaddr*)&local,sizeof(local));
    if(n < 0)
    {
        std::cerr << "bind socket fail!";
        return -1;
    }
    std::cerr << "bind socket success!" << std::endl;

    while(true)
    {
        sockaddr_in from;
        socklen_t len = sizeof(from);
        char buffer[1024];
        int n = ::recvfrom(socketfd,buffer,sizeof(buffer),0,(sockaddr*)&from,&len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << "client say# " << buffer << std::endl;
            //回显消息
            ::sendto(socketfd,buffer,sizeof(buffer),0,(sockaddr*)&from,len);
        }
    }
    return 0;
}